<script lang="ts" setup>
import { get, post, message, loadFile, checkBtnPermission } from '@/utils'
import navbar from '@/assets/images/navbar.png'
import { FormInstance } from '@arco-design/web-vue'
import { BtnPermission } from '@/enum/permission'
import keyword from '@/assets/images/keyword.png'
interface Menu {
  name: string
  subButtons: Menu[]
  type: 'click' | 'view' | 'miniprogram'
  key: any
  url: string
  appid: string
  pagepath: string
  timestamp: number
}
const getTimestamp = () => new Date().getTime()
const button = ref([] as Menu[])
const emptyItem = {
  name: '菜单',
  type: 'click',
  key: '',
  url: '',
  appid: '',
  pagepath: '',
} as Menu
const addMenu = () => {
  if (!checkBtnPermission(BtnPermission.新建)) return
  const fn = () => {
    if (button.value.length < 3) {
      const timestamp = getTimestamp()
      button.value.push({
        ...emptyItem,
        timestamp,
        subButtons: [],
      })
      active.value = timestamp
    }
  }

  if (button.value.length == 0) {
    fn()
  } else {
    if (formRef.value) {
      formRef.value.validate(err => {
        if (!err) {
          fn()
        }
      })
    } else fn()
  }
}
const addSubMenu = index => {
  if (!checkBtnPermission(BtnPermission.新建)) return
  formRef.value.validate(err => {
    if (!err) {
      const timestamp = getTimestamp()
      console.log('🚀 ~ addSubMenu ~ timestamp:', timestamp)
      button.value[index].subButtons.push({ ...emptyItem, timestamp })
      active.value = timestamp
      console.log('🚀 ~ addSubMenu ~ button:', button)
    }
  })
}
const active = ref(-1)
const formRef = ref() as Ref<FormInstance>
const handleSave = () => {
  if (!checkBtnPermission(BtnPermission.编辑)) return

  console.log('🚀 ~ handleSave ~ query:', button.value)
  // return
  formRef.value.validate(err => {
    if (!err) {
      post({ url: '/server-base/admin/wx/menu/create', data: { buttons: button.value } }, ({ code, msg }) => {
        message({
          type: code == 200 ? 'success' : 'error',
          content: msg,
        })
        if (code == 200) {
          getInfo()
        }
      })
    }
  })
}
watch(
  () => active.value,
  (newVal, oldVal) => {
    console.log('🚀 ~ newVal,oldVal:', newVal, oldVal)
    /**处理点击的时候获取点击项的数据渲染到表单 */
    console.log('🚀 ~ button:', button)
    let formData: any = {}
    button.value.map((menu, menuIndex) => {
      if (menu.timestamp == newVal) {
        formData = menu
      } else {
        menu.subButtons.map((subMenu, index) => {
          if (subMenu.timestamp == newVal) {
            formData = subMenu
          }
        })
      }
    })
    Object.assign(detail, formData)
  }
)
const detail = computed(() => {
  let formData: any = {}

  button.value.map((menu, menuIndex) => {
    if (menu.timestamp == active.value) {
      formData = menu
    } else {
      menu.subButtons.map((subMenu, index) => {
        if (subMenu.timestamp == active.value) {
          formData = subMenu
        }
      })
    }
  })
  console.log('🚀 ~ detail ~ formData:', formData)
  return formData
})
const getInfo = () => {
  get({ url: '/server-base/admin/wx/menu/list' }, ({ data }) => {
    console.log(data)
    const list: Menu[] = []
    /**处理数据
     * 插入一个自定义参数时间戳 用来做处理
     */
    data.selfMenuInfo.buttons.forEach((item, index) => {
      const subButtons: Menu[] = []
      if (Array.isArray(item.subButtons.subButtons)) {
        item.subButtons.subButtons.forEach((subMenu, index2) => {
          subButtons.push({
            ...subMenu,
            timestamp: getTimestamp() + '-subMenu-' + index2,
            subButtons: [],
          })
        })
        list.push({
          ...item,
          timestamp: getTimestamp() + '-' + index,
          subButtons,
        })
      } else {
        list.push({
          ...item,
          timestamp: getTimestamp() + index,
          subButtons: [],
        })
        active.value = getTimestamp() + index
      }
    })
    button.value = list
  })
}
getInfo()
const onRemove = () => {
  const index = button.value.findIndex(f => f.timestamp == detail.value.timestamp)
  if (index != -1) {
    button.value.splice(index, 1)
    active.value = -1
  } else {
    button.value.map((item, itemIndex) => {
      const _index = item.subButtons.findIndex(f => f.timestamp == detail.value.timestamp)
      if (_index != -1) {
        button.value[itemIndex].subButtons.splice(_index, 1)
        active.value = item.timestamp
      }
    })
  }
}
const onClick = key => {
  if (active.value == -1) {
    active.value = key
  } else {
    formRef.value.validate(err => {
      if (!err) {
        active.value = key
      }
    })
  }
}
</script>
<template>
  <a-card>
    <div class="page flex">
      <div class="view-mobile flex-js flex-c">
        <img class="navbar" :src="navbar" />
        <div class="tabbar grid-3">
          <template v-for="(menu, i) in button">
            <div :class="['item', active == menu.timestamp ? 'active' : '']" @click="onClick(menu.timestamp)">
              <span>{{ menu.name }}</span>
              <div class="menu-list">
                <div :class="['item', active == item.timestamp ? 'active' : '']" v-for="item in menu.subButtons" @click.stop="onClick(item.timestamp)">
                  {{ item.name }}
                </div>
                <div class="btn flex" @click.stop="addSubMenu(i)">
                  <icon-plus style="margin: auto" />
                </div>
                <div class="icon">
                  <icon-caret-down />
                </div>
              </div>
            </div>
          </template>

          <div class="btn flex" @click="addMenu()" v-if="button.length < 3">
            <icon-plus style="margin: auto" />
          </div>
        </div>
        <img class="keyword" :src="keyword" />
      </div>
      <div class="form">
        <div class="title flex-js flex-center">
          <p>菜单信息</p>
          <a-button type="primary" status="danger" @click="onRemove" :disabled="active == -1">删除</a-button>
        </div>
        <a-form :model="detail" ref="formRef" :disabled="active == -1">
          <a-form-item label="菜单名称" field="name" :rules="[{ required: true, message: '请输入菜单名称' }]" :validate-trigger="['change', 'blur']">
            <a-input v-model="detail.name" placeholder="请输入菜单名称" />
          </a-form-item>
          <template v-if="!detail.subButtons?.length">
            <a-form-item label="规则状态" field="type" :rules="[{ required: true, message: '请选择规则状态' }]" :validate-trigger="['change', 'blur']">
              <a-select
                v-model="detail.type"
                placeholder="请选择"
                :options="[
                  { label: '跳转网页', value: 'view' },
                  { label: '点击', value: 'click' },
                  { label: '跳转小程序', value: 'miniprogram' },
                ]"
              />
            </a-form-item>
            <a-form-item v-if="detail.type == 'click'" label="关键字" field="key" :rules="[{ required: true, message: '请输入关键字' }]" :validate-trigger="['change', 'blur']">
              <a-input v-model="detail.key" placeholder="请输入关键字" />
            </a-form-item>
            <a-form-item v-else-if="detail.type == 'view'" label="跳转地址" field="url" :rules="[{ required: true, message: '请输入关键字' }]" :validate-trigger="['change', 'blur']">
              <a-input v-model="detail.url" placeholder="请输入关键字" />
            </a-form-item>
            <template v-else-if="detail.type == 'miniprogram'">
              <a-form-item label="appid" field="appid" :rules="[{ required: true, message: '请输入appid' }]" :validate-trigger="['change', 'blur']">
                <a-input v-model="detail.appid" placeholder="请输入appid" />
              </a-form-item>
              <a-form-item label="备用网页" field="pagepath" :rules="[{ required: true, message: '请输入备用网页' }]" :validate-trigger="['change', 'blur']">
                <a-input v-model="detail.pagepath" placeholder="请输入备用网页" />
              </a-form-item>
              <a-form-item label="小程序路径" field="url" :rules="[{ required: true, message: '请输入小程序路径' }]" :validate-trigger="['change', 'blur']">
                <a-input v-model="detail.url" placeholder="请输入小程序路径" />
              </a-form-item>
            </template>
          </template>

          <a-form-item label="">
            <a-button type="primary" long @click="handleSave">保存并启用该配置</a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </a-card>
</template>
<style lang="less" scoped>
.page {
  padding: 0 100px;

  .view-mobile {
    background-color: #f9f9f9;
    height: 560px;
    width: 300px;
    position: relative;

    .keyword {
      left: 0;
      width: 100%;
      position: absolute;
      bottom: 0;
    }
    .tabbar {
      position: relative;
      z-index: 2;
      line-height: 48px;
      padding-left: 40px;
      text-align: center;

      .btn,
      .item {
        cursor: pointer;
        border: 1px solid #e7e7eb;
        height: 50px;
        position: relative;
        &.active {
          border: 1px solid #44b549;
        }
        .menu-list {
          position: absolute;
          bottom: 60px;
          width: 100%;
          .icon {
            position: absolute;
            bottom: 0;
            font-size: 20px;
            color: white;
            width: 20px;
            height: 20px;
            left: 0;
            right: 0;
            margin: auto;
          }
        }
      }
    }
  }
  .form {
    width: 500px;
    margin-left: 100px;
    .title {
      padding-bottom: 10px;
      margin-bottom: 10px;
      border-bottom: 1px solid #f7f7f7;
    }
  }
}
</style>
